package com.wk.controller;

import com.wk.entity.CmfzBanner;
import com.wk.service.CmfzBannerService;
import com.wk.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("banner")
@Slf4j
public class BannerController {

    @Autowired
    private CmfzBannerService cmfzBannerService;

    @Autowired
    private UploadService uploadService;


    @CrossOrigin
    @RequestMapping("findAll")
    public Map findAll(Integer page,Integer limit,String name){
        log.info("查询所有轮播图信息");
        int i =1;
        int j = 0;
        System.out.println(i/j);
        return cmfzBannerService.findAll(page,limit,name);
    }

    @RequiresRoles("superadmin")
    @RequestMapping("add")
    public Map add(MultipartFile picture1, CmfzBanner cmfzBanner, HttpServletRequest request){

        log.info("添加一个轮播图");

        Map map = new HashMap();

        String originalFilename  =  uploadService.upload(picture1,request);


        if(originalFilename!=null){
            cmfzBanner.setBannerDate(new Date());
            cmfzBanner.setBannerImageUrl(originalFilename);
            map = cmfzBannerService.insert(cmfzBanner);
        }else{
            map.put("data","图片上传失败!");
            log.error("图片上传失败");
        }

        return map;
    }

    @RequiresRoles("superadmin")
    @CrossOrigin
    @RequestMapping("findOne")
    public Map findOne(Integer id){
        return cmfzBannerService.findOne(id);
    }

    @RequiresRoles("superadmin")
    @RequestMapping("delete")
    public Map delete(Integer id){
        return cmfzBannerService.delete(id);
    }

    @RequestMapping("update")
    public Map update(MultipartFile picture2,HttpServletRequest request,CmfzBanner cmfzBanner){

        log.info("接收到的banner对象"+cmfzBanner);

        Map map = new HashMap();

        String originalFilename = picture2.getOriginalFilename();

        if("".equals(originalFilename)){
            map = cmfzBannerService.update(cmfzBanner);
        }else{
            originalFilename = uploadService.upload(picture2,request);
            cmfzBanner.setBannerImageUrl(originalFilename);
            cmfzBanner.setBannerDate(new Date());
            map =  cmfzBannerService.update(cmfzBanner);
        }
        return map;
    }
}
